﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using fanfu.Common;
using fanfu.Model;
using fanfu.Business;
using System.Data.SqlClient;

public partial class Review : BasePage
{
    //所有评论信息
    private DataTable __Review = new DataTable();
    //评论信息预览
    public string strReviewMsg = string.Empty;

    #region 自定义
    /// <summary>
    /// 绑定查询后的数据到Repeater
    /// </summary>
    /// <param name="rptDataList">要绑定的Repeater对象</param>
    /// <param name="page">设置当前页,从1开始</param>
    private void BindDataBySearch(Repeater rptDataList, int page)
    {
        #region 获取查询条件

        //获取查询条件
        string reviewerName = this.searchReviewerName.Value.Trim();
        string parentName = this.searchParentName.Value.Trim();
        string reviewContent = this.searchReviewContent.Value.Trim();
        string startTime = this.searchStartCreateTime.Value.Trim();
        string endTime = this.searchEndCreateTime.Value.Trim();
        byte parentType = byte.Parse(this.searchParentType.SelectedItem.Value);
        byte flag = byte.Parse(this.searchFlag.SelectedItem.Value);
        #endregion

        #region 创建查询SQL语句和查询条件参数

        //创建查询SQL语句和查询条件参数
        string sqlString = "SELECT * FROM Review WHERE 1=1 ";
        List<SqlParameter> paraList = new List<SqlParameter>();

        if (reviewerName != "")
        {
            sqlString += "AND ReviewerName like @ReviewerName ";
            paraList.Add(new SqlParameter("@ReviewerName", "%" + reviewerName + "%"));
        }
        if (parentName != "")
        {
            sqlString += "AND ParentName like @ParentName ";
            paraList.Add(new SqlParameter("@ParentName", "%" + parentName + "%"));
        }
        if (reviewContent != "")
        {
            sqlString += "AND ReviewContent like @ReviewContent ";
            paraList.Add(new SqlParameter("@ReviewContent", "%" + reviewContent + "%"));
        }
        if (startTime != "")
        {
            sqlString += "AND ReviewTime>=@StartCreateTime ";
            paraList.Add(new SqlParameter("@StartCreateTime", Convert.ToDateTime(startTime)));
        }
        if (endTime != "")
        {
            sqlString += "AND ReviewTime<@EndCreateTime ";
            paraList.Add(new SqlParameter("@EndCreateTime", Convert.ToDateTime(endTime).AddDays(1)));
        }
        if (parentType != 0)
        {
            sqlString += "AND ParentType=@ParentType ";
            paraList.Add(new SqlParameter("@ParentType", parentType));
        }
        if (flag != 0)
        {
            sqlString += "AND Flag=@Flag ";
            paraList.Add(new SqlParameter("@Flag", flag));
        }
        sqlString += "ORDER BY ReviewTime ASC";
        #endregion

        //给数据列表赋值
        __Review = SqlHelper.GetDataTable(sqlString, paraList.ToArray());
        PagedDataSource pds = new PagedDataSource();
        pds.DataSource = __Review.DefaultView;
        pds.AllowPaging = true;
        pds.PageSize = __AdminPageSize;
        pds.CurrentPageIndex = page - 1;
        rptDataList.DataSource = pds;
        rptDataList.DataBind();

        //创建的分页HTML并赋值给前台
        this.paging.InnerHtml = CreateAdminPaging(__Review.Rows.Count, page);
        //清理控件状态
        ClearInputState();
    }

    /// <summary>
    /// 绑定全部数据到Repeater
    /// </summary>
    /// <param name="rptDataList">要绑定的Repeater对象</param>
    /// <param name="page">设置当前页,从1开始</param>
    private void BindAllData(Repeater rptDataList, int page)
    {
        //清理查询框数据,避免单击页码时产生错误条件
        this.searchReviewerName.Value = "";
        this.searchParentName.Value = "";
        this.searchReviewContent.Value = "";
        this.searchStartCreateTime.Value = "";
        this.searchEndCreateTime.Value = "";
        this.searchParentType.SelectedIndex = 0;
        this.searchFlag.SelectedIndex = 0;

        //给数据列表赋值
        __Review = new ReviewRule().GetAllReviewInfo();
        PagedDataSource pds = new PagedDataSource();
        pds.DataSource = __Review.DefaultView;
        pds.AllowPaging = true;
        pds.PageSize = __AdminPageSize;
        pds.CurrentPageIndex = page - 1;
        rptDataList.DataSource = pds;
        rptDataList.DataBind();

        //创建的分页HTML并赋值给前台
        this.paging.InnerHtml = CreateAdminPaging(__Review.Rows.Count, page);
        //清理控件状态
        ClearInputState();
    }

    /// <summary>
    /// 清理控件状态
    /// </summary>
    private void ClearInputState()
    {
        this.editID.Value = "";             //清除编辑的ID
        this.deleteID.Value = "";           //清除删除的ID
        this.lockIP.Value = "";             //清除封杀的IP
        RunJavascript("ResetInput();", true);//JS清空控件值
    }
    #endregion

    #region 更新最新评论总数到文章表
    /// <summary>
    /// 更新最新评论总数到文章表
    /// </summary>
    /// <param name="reviewID">当前操作的评论</param>
    private void CommentCountUpdate(string reviewID)
    {
        ReviewModel reviewModel = new ReviewRule().GetReviewByID(reviewID);
        new ArticleRule().ArticleCommentCountUpdate(reviewModel.ParentId.ToString(), new ReviewRule().GetReviewByParentId(reviewModel.ParentId.ToString(), (int)ReviewParentType.article).Rows.Count);
    }
    #endregion

    #region 页面加载
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //绑定评论类型到下拉列表
            EnumPlus.BindDesEnumToListControl(this.searchParentType, typeof(ReviewParentType));
            //绑定评论状态到下拉列表
            EnumPlus.BindDesEnumToListControl(this.searchFlag, typeof(ReviewFlag));
            EnumPlus.BindDesEnumToListControl(this.drpFlag, typeof(ReviewFlag));
            this.drpFlag.Items.RemoveAt(0);
            
            //判断请求是否来自查看新消息
            if (string.IsNullOrEmpty(Request.QueryString["news"]))
            {
                this.searchFlag.SelectedIndex = 0;
                BindAllData(this.rptDataList, 1);
            }
            else if (Request.QueryString["news"] == "noRead")
            {
                this.searchFlag.Items.FindByValue(((byte)ReviewFlag.noRead).ToString()).Selected = true;
                BindDataBySearch(this.rptDataList, 1);
            }
        }
        else
        {
            string controlName = Request.Params.Get("__EVENTTARGET");
            string eventArgument = Request.Params.Get("__EVENTARGUMENT");
            //请求是否来自分页
            if (controlName == "pagecut" && eventArgument != "")
            {
                int current = Convert.ToInt32(eventArgument);
                //绑定列表并转到请求页
                BindDataBySearch(this.rptDataList, current);
            }
        }
    }
    #endregion

    #region 已经阅读
    protected void lbtnPass_Click(object sender, EventArgs e)
    {
        string sqlString = string.Format("UPDATE Review SET Flag={0} WHERE ID={1}", (int)ReviewFlag.read, this.editID.Value);
        int result = SqlHelper.ExecuteCommand(sqlString);
        if (result == 1)
        {
            RunJavascript("PopupMsg('success','恭喜您,修改已阅成功！');", true);
            //获取删除后评论的总和更新到文章表
            CommentCountUpdate(this.editID.Value);
        }
        else
            RunJavascript("PopupMsg('error','错误,修改已阅失败！');", true);
        
        //刷新页面,更新消息数
        Response.Redirect("Review.aspx");
    }
    #endregion

    #region 回复事件
    protected void lbtnReply_Click(object sender, EventArgs e)
    {

        //更改为已阅读状态
        string sqlString = string.Format("UPDATE Review SET Flag={0} WHERE ID={1}", (int)ReviewFlag.read, this.editID.Value);
        int result = SqlHelper.ExecuteCommand(sqlString);
        //获取删除后评论的总和更新到文章表
        CommentCountUpdate(this.editID.Value);

        //设置我的回复的那条回复记录状态为:我的回答
        this.drpFlag.ClearSelection();
        this.drpFlag.Items.FindByValue(((int)ReviewFlag.myAnswer).ToString()).Selected = true;

        //选项卡跳转
        RunJavascript("window.onload=function(){$('.box_title_tabs li').eq(1).click();};", true);

        string editID = this.editID.Value;
        if (!string.IsNullOrEmpty(editID))
        {
            ReviewModel review = new ReviewRule().GetReviewByID(editID);

            //显示评论信息到页面
            strReviewMsg += "<li><strong>留言ID：</strong>" + review.ID + "</li>";
            strReviewMsg += "<li><strong>留言标题：</strong>" + review.ParentName + "</li>";
            strReviewMsg += "<li><strong>评论父ID：</strong>" + review.ParentId + "</li>";
            string strType = review.ParentType.ToString() == "1" ? "文章" : "图片";
            strReviewMsg += "<li><strong>评论类型：</strong>" + strType + "</li>";
            strReviewMsg += "<li><strong>叠楼ID：</strong>" + review.BaseId + "</li>";
            strReviewMsg += "<li><strong>评论者：</strong>" + review.ReviewerName + "</li>";
            strReviewMsg += "<li><strong>评论邮箱：</strong>" + review.ReviewerEmail + "</li>";
            strReviewMsg += "<li><strong>评论网址：</strong>" + review.ReviewerUrl + "</li>";
            strReviewMsg += "<li><strong>评论IP：</strong>" + review.ReviewerIP + "</li>";
            strReviewMsg += "<li><strong>评论内容：</strong>" + review.ReviewContent + "</li>";
            strReviewMsg += "<li><strong>评论时间：</strong>" + review.ReviewTime.ToString() + "</li>";
            strReviewMsg += "<li><strong>评论状态：</strong>" + new ReviewRule().GetFlagDes(review.Flag) + "</li>";
            this.txtParentId.Value = review.ParentId.ToString();
            this.txtParentType.Value = review.ParentType.ToString();
            this.txtParentName.Value = review.ParentName;
        }
    }
    #endregion

    #region 删除事件
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        int result = 0;
        string deleteItems = this.deleteID.Value;
        if (!string.IsNullOrEmpty(deleteItems))
        {
            string[] values = deleteItems.Split(',');
            foreach (string item in values)
            {
                result += new ReviewRule().DeleteReview(item);
                //获取删除后评论的总和更新到文章表
                CommentCountUpdate(item);
            }
            if (result == values.Length)
            {
                RunJavascript("PopupMsg('success','恭喜您,删除成功！');", true);
            }
            else
            {
                RunJavascript("PopupMsg('error','错误,删除失败！');", true);
            }
        }

        //刷新页面,更新消息数
        Response.Redirect("Review.aspx");
    }
    #endregion

    #region 封杀IP
    protected void lbtnLockIP_Click(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(this.lockIP.Value.Trim()))
        {
            int result = new BrowseLimitRule().InsertBrowseLimit(this.lockIP.Value.Trim());
            if (result == 1)
            {
                RunJavascript("PopupMsg('success','恭喜您,封杀IP成功！');", true);
            }
            else
            {
                RunJavascript("PopupMsg('error','错误,封杀IP失败！');", true);
            }

            //清理控件状态
            ClearInputState();
        }
    }
    #endregion

    #region 保存事件
    protected void btnSave_Click(object sender, EventArgs e)
    {
        string parentName = this.txtParentName.Value;
        int parentId = int.Parse(this.txtParentId.Value);
        byte parentType = byte.Parse(this.txtParentType.Value);
        int baseId = int.Parse(this.editID.Value);
        string reviewerName = this.txtReviewerName.Value.Trim();
        string reviewerEmail = this.txtReviewerEmail.Value;
        string reviewerUrl = this.txtReviewerUrl.Value;
        if (string.IsNullOrEmpty(reviewerName))
            reviewerName = CookieHelper.GetCookie("userAlias");
        if (string.IsNullOrEmpty(reviewerEmail))
            reviewerEmail = "fanfu1988@163.com";
        //获取IP信息
        string reviewerIP = System.Web.HttpContext.Current.Request.UserHostAddress;
        IPLocation ipLocation = new QQWryLocator().Query(reviewerIP);
        reviewerIP = ipLocation.IP + ipLocation.Country + ipLocation.Local;
        string reviewContent = this.txtReviewContent.Value;
        DateTime reviewTime = DateTime.Now;
        byte flag = byte.Parse(this.drpFlag.SelectedItem.Value);

        //回复评论
        ReviewModel review = new ReviewModel();
        review.ParentName = parentName;
        review.ParentId = parentId;
        review.ParentType = parentType;
        review.BaseId = baseId;
        review.ReviewerName = reviewerName;
        review.ReviewerEmail = reviewerEmail;
        review.ReviewerUrl = reviewerUrl;
        review.ReviewerIP = reviewerIP;
        review.ReviewContent = reviewContent;
        review.ReviewTime = reviewTime;
        review.Flag = flag;

        int result = SqlHelper.ExecuteCommand(ReviewModel.GetInsertSQL(), review.ToSqlParameters());
        if (result == 1)
        {
            RunJavascript("PopupMsg('success','恭喜您,回复成功！');", true);
        }
        else
        {
            RunJavascript("PopupMsg('error','错误,回复失败！');", true);
            RunJavascript("window.onload=function(){$('.box_title_tabs li').eq(1).click();};", true);
        }

        //刷新页面,更新消息数
        Response.Redirect("Review.aspx");
    }
    #endregion

    #region 查询事件
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        //绑定列表并转到第一页
        BindDataBySearch(this.rptDataList, 1);
    }
    #endregion
}